package lpg;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import lpg.util.Utility;

class InputFileSymbol extends Symbol
{
    InputFileSymbol(String name, int poolIndex)
    {
        super(name, poolIndex);
    }

    void lock()
    {
        locked = true;
    }

    void unlock()
    {
        locked = false;
    }

    boolean isLocked()
    {
        return locked;
    }

    void readInput()
    {
        if (buffer != null) // file already read in
        {
            return;
        }

        StringBuilder buf = new StringBuilder();
        char[] block = new char[65536];
        FileInputStream fis = null;
        try
        {
            fis = new FileInputStream(name());
            BufferedReader reader = new BufferedReader(new InputStreamReader(fis, Utility.getCharset()));

            int len;
            while ((len = reader.read(block)) != -1)
            {
                buf.append(block, 0, len);
            }

            reader.close();
            fis = null;
        }
        catch (IOException e)
        {
            return;
        }
        finally
        {
            Utility.close(fis);
        }

        int sourceTail = buf.length() - 1;  // point to last character read from the file.
        //
        // Remove all trailing spaces
        //
        while (sourceTail >= 0 && Character.isWhitespace(buf.charAt(sourceTail)))
            sourceTail--;

        buffer = new char[++sourceTail + 1];
        buf.getChars(0, sourceTail, buffer, 0);
        buffer[sourceTail] = '\n'; // add end-of-line
    }

    IntArrayList lineLocation()
    {
        return lineLocation;
    }

    int lineLocation(int index)
    {
        return lineLocation.get(index);
    }

    char[] buffer()
    {
        return buffer;
    }

    private IntArrayList lineLocation = new IntArrayList();
    private boolean locked = false;
    private char[] buffer = null;

}
